/*
 *  Copyright (C) 2010 takaji
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 * 
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 * 
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/*
 * GeneralLedgerReportView.java
 *
 * Created on Jan 8, 2010, 2:26:57 PM
 */
package dakside.hacc.modules.accounting.reports;

import dakside.hacc.core.models.Account;
import dakside.hacc.core.models.AccountEntry;
import dakside.hacc.core.models.AccountPeriod;
import dakside.hacc.core.models.comparators.AccountComparator;
import dakside.hacc.core.models.comparators.AccountPeriodComparator;
import org.dakside.duck.helpers.SwingHelper;
import dakside.hacc.modules.accounting.accountposting.AccountingController;
import org.dakside.utils.ResourceCentre;
import java.awt.Component;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.logging.Logger;
import org.dakside.duck.plugins.AppConstants;
import org.dakside.duck.plugins.Command;
import org.dakside.duck.plugins.DefaultCommandInvoker;
import org.dakside.duck.plugins.ToolbarContainer;

/**
 * 
 * @author takaji
 */
public class GeneralLedgerReportView extends javax.swing.JPanel implements ToolbarContainer {

    private static final Logger logger = Logger.getLogger(GeneralLedgerReportView.class.getName());
    private ResourceCentre rc = ResourceCentre.getInstance(this);
    AccountingController accountingController = new AccountingController();

    /** Creates new form GeneralLedgerReportView */
    public GeneralLedgerReportView() {
        initComponents();
        refresh();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        customToolbar = new javax.swing.JToolBar();
        jToolBar1 = new javax.swing.JToolBar();
        jLabel1 = new javax.swing.JLabel();
        cboAccount = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();
        cboPeriod = new javax.swing.JComboBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        accountEntryTable1 = new dakside.hacc.modules.accounting.reports.AccountEntryTable();

        customToolbar.setFloatable(false);
        customToolbar.setRollover(true);
        customToolbar.setName("customToolbar"); // NOI18N

        jToolBar1.setRollover(true);
        jToolBar1.setName("jToolBar1"); // NOI18N

        jLabel1.setText("Account");
        jLabel1.setName("jLabel1"); // NOI18N
        jToolBar1.add(jLabel1);

        cboAccount.setName("cboAccount"); // NOI18N
        cboAccount.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cboAccountItemStateChanged(evt);
            }
        });
        jToolBar1.add(cboAccount);

        jLabel2.setText("Period");
        jLabel2.setName("jLabel2"); // NOI18N
        jToolBar1.add(jLabel2);

        cboPeriod.setName("cboPeriod"); // NOI18N
        cboPeriod.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cboPeriodItemStateChanged(evt);
            }
        });
        jToolBar1.add(cboPeriod);

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        accountEntryTable1.setModel(new AccountEntryTableModel());
        accountEntryTable1.setName("accountEntryTable1"); // NOI18N
        jScrollPane1.setViewportView(accountEntryTable1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 286, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void cboAccountItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cboAccountItemStateChanged
        reloadEntries();
    }//GEN-LAST:event_cboAccountItemStateChanged

    private void cboPeriodItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cboPeriodItemStateChanged
        // TODO add your handling code here:
        reloadEntries();
    }//GEN-LAST:event_cboPeriodItemStateChanged
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private dakside.hacc.modules.accounting.reports.AccountEntryTable accountEntryTable1;
    private javax.swing.JComboBox cboAccount;
    private javax.swing.JComboBox cboPeriod;
    private javax.swing.JToolBar customToolbar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JToolBar jToolBar1;
    // End of variables declaration//GEN-END:variables

    private void reloadEntries() {
        Account acc = cboAccount.getSelectedItem() instanceof Account
                ? (Account) cboAccount.getSelectedItem() : null;
        AccountPeriod period = cboPeriod.getSelectedItem() instanceof AccountPeriod
                ? (AccountPeriod) cboPeriod.getSelectedItem() : null;

        AccountEntry[] entries = accountingController.getAccountEntriesOf(acc, period);
        accountEntryTable1.load(entries);
    }

    /**
     * Refresh view
     * (Init account list and accountPeriod list comboboxes)
     */
    public final void refresh() {
        Object currentPeriod = null;
        if (cboPeriod.getItemCount() > 0) {
            currentPeriod = cboPeriod.getSelectedItem();
        }
        Object currentAccount = null;
        if (cboAccount.getItemCount() > 0) {
            currentAccount = cboAccount.getSelectedItem();
        }

        Account[] allAccounts = accountingController.getAllAccounts();
        AccountPeriod[] periods = accountingController.getAllOpeningPeriods();
        //ignore account type=folder
        ArrayList displayAccounts = new ArrayList(allAccounts.length);
        for (Account account : allAccounts) {
            if (account != null && account.getType() != Account.TYPE_FOLDER) {
                displayAccounts.add(account);
            }
        }
        Collections.sort(displayAccounts, AccountComparator.getAscInstance());
        displayAccounts.add(0, rc.getString("All"));
        //sort account period
        Arrays.sort(periods, AccountPeriodComparator.getAscInstance());

        if (currentPeriod == null) {
            for (AccountPeriod period : periods) {
                if (period != null && AccountPeriod.CURRENT.equals(period.getState())) {
                    currentPeriod = period;
                }
            }
        }

        //add all periods
        ArrayList displayPeriods = new ArrayList(periods.length + 1);
        displayPeriods.add(rc.getString("All"));
        Collections.addAll(displayPeriods, periods);

        SwingHelper.initCombobox(cboAccount, displayAccounts.toArray(), currentAccount);
        SwingHelper.initCombobox(cboPeriod, displayPeriods.toArray(), currentPeriod);
    }
    //TOOLBAR CONTAINER SUPPORT
    private Component[] toolbar;

    public Component[] getToolbarItems() {
        if (toolbar == null) {
            toolbar = customToolbar.getComponents();
        }
        return toolbar;
    }
    private DefaultCommandInvoker myInvoker = null;

    public final synchronized DefaultCommandInvoker getInvoker() {
        if (myInvoker == null) {
            myInvoker = new DefaultCommandInvoker();
        }
        myInvoker.add(AppConstants.Commands.REFRESH, new Command() {

            public Object invoke(Object[] args) {
                refresh();
                return true;
            }
        });
        return myInvoker;
    }
    //END OF TOOLBAR CONTAINER SUPPORT
}
